package cn.crystalorigin.plugin.util

class MSTimer {
    /**
     * Use a long-typed variable to record the time we last synchronized.
     */
    var current = System.currentTimeMillis(); private set

    /**
     * Reset the check point.
     * @param offset extra delta
     * @return the value of current time value
     */
    fun reset(offset: Long = 0L) {
        current = System.currentTimeMillis() + offset
    }

    /**
     * Check whether the time has passed the given parameter or not.
     * @param time the time we are going to check
     * @param timeUnit the unit of time we use
     */
    fun check(time: Long, timeUnit: TimeUnit = TimeUnit.MILLISECOND): Boolean {
        val currentValue = current
        val currentTime = System.currentTimeMillis()
        return (currentTime - currentValue) >= time * timeUnit.multiplier
    }

    fun check(time: Int, timeUnit: TimeUnit = TimeUnit.MILLISECOND) = this.check(time.toLong(), timeUnit)

    /**
     * Check whether the time has passed the given parameter or not.
     * If true, then we reset the value.
     * @param time the time we are going to check
     * @param timeUnit the unit of time we use
     */
    fun checkAndReset(time: Long,
                      timeUnit: TimeUnit = TimeUnit.MILLISECOND,
                      offset: Long = 0L): Boolean {
        return check(time, timeUnit).also {
            if (it) reset(offset)
        }
    }

    fun checkAndReset(time: Int,
                      timeUnit: TimeUnit = TimeUnit.MILLISECOND,
                      offset: Long = 0L): Boolean = checkAndReset(time.toLong(), timeUnit, offset)
}

enum class TimeUnit(val multiplier: Int) {
    MILLISECOND(1),
    SECOND(1000),
    MINUTE(1000 * 60),
    HOUR(1000 * 60 * 60),
}